package cn.stylefeng.guns.modular.rest;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.comm.util.DateUtils;
import cn.stylefeng.guns.modular.comm.entity.MoneyHistory;
import cn.stylefeng.guns.modular.comm.entity.WxMiniUser;
import cn.stylefeng.guns.modular.comm.service.MoneyHistoryService;
import cn.stylefeng.guns.modular.comm.service.WxMiniUserService;
import cn.stylefeng.guns.modular.school.entity.ParkingInfo;
import cn.stylefeng.guns.modular.school.entity.ParkingPlaceInfo;
import cn.stylefeng.guns.modular.school.entity.ParkingPlaceUseInfo;
import cn.stylefeng.guns.modular.school.model.params.ParkingPlaceUseInfoParam;
import cn.stylefeng.guns.modular.school.model.result.ParkingPlaceUseInfoResult;
import cn.stylefeng.guns.modular.school.service.ParkingInfoService;
import cn.stylefeng.guns.modular.school.service.ParkingPlaceInfoService;
import cn.stylefeng.guns.modular.school.service.ParkingPlaceUseInfoService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 绑定控制器
 *
 * @author
 * @Date 2019-11-18 13:24:11
 */
@RestController
@RequestMapping("/gunsApi/parking/place/use")
public class ApiNeedTokenParkingPlaceUseController extends BaseController {

    // 停车位使用情况
    @Autowired
    private ParkingPlaceUseInfoService parkingPlaceUseInfoService;
    // 停车位
    @Autowired
    private ParkingPlaceInfoService parkingPlaceInfoService;
    // 停车场
    @Autowired
    private ParkingInfoService parkingInfoService;
    @Autowired
    private WxMiniUserService wxMiniUserService;
    @Autowired
    private MoneyHistoryService moneyHistoryService;

    /**
     * 订单详情
     *
     * @param id 订单id
     * @return
     */
    @GetMapping(value = "detail")
    public Object detail(Integer id) {
        Map map = new HashMap();
        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getById(id);
        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfo.getParkingPlaceId());
        ParkingInfo parkingInfo = parkingInfoService.getById(parkingPlaceInfo.getParkingId());
        map.put("parkingPlaceUseInfo", parkingPlaceUseInfo);
        map.put("parkingPlaceInfo", parkingPlaceInfo);
        map.put("parkingInfo", parkingInfo);
        // 已支付的时候直接显示停车时长和费用
        if (parkingPlaceUseInfo != null && StringUtils.equals("0", parkingPlaceUseInfo.getPayFlag())) {
            int hour = DateUtils.distanceHour(parkingPlaceUseInfo.getPayTime(), parkingPlaceUseInfo.getParkStartTime());
            map.put("needPayPrice", parkingPlaceUseInfo.getMoney());
            map.put("parking_hour", hour);
        }
        // 未支付的时候计算需要支付的价格和停车时长
        else if (parkingPlaceUseInfo != null && parkingPlaceUseInfo.getParkStartTime() != null) {
            int hour = DateUtils.distanceHour(DateUtils.getSystemDate(), parkingPlaceUseInfo.getParkStartTime());
            // ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfo.getParkingPlaceId());
            int needPayPrice = parkingPlaceInfo.getPrice() * hour;
            map.put("needPayPrice", needPayPrice == 0 ? parkingPlaceInfo.getPrice() : needPayPrice);
            map.put("parking_hour", hour);
        }
        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    @GetMapping(value = "list")
    public Object list(String openId) {
        Map map = new HashMap();
        List<ParkingPlaceUseInfoResult> list = new ArrayList<>();
        List<ParkingPlaceUseInfo> parkingPlaceUseInfos = parkingPlaceUseInfoService.list(new QueryWrapper<ParkingPlaceUseInfo>().eq("open_id", openId).orderByDesc("create_time"));
        parkingPlaceUseInfos.forEach(parkingPlaceUseInfo -> {
            ParkingPlaceUseInfoResult parkingPlaceUseInfoResult = new ParkingPlaceUseInfoResult();
            ToolUtil.copyProperties(parkingPlaceUseInfo, parkingPlaceUseInfoResult);
            list.add(parkingPlaceUseInfoResult);

            ParkingInfo parkingInfo = parkingInfoService.getById(parkingPlaceUseInfo.getParkingId());
            parkingPlaceUseInfoResult.setParkingName(parkingInfo == null ? "" : parkingInfo.getName());

            ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfo.getParkingPlaceId());
            parkingPlaceUseInfoResult.setParkingPlaceStatus(parkingPlaceInfo.getStatus());
            parkingPlaceUseInfoResult.setLocation(parkingPlaceInfo.getLocation());
            if (parkingPlaceUseInfo.getPayFlag().equals("0")) {
                parkingPlaceUseInfoResult.setParkingPlaceStatusStr("已完成");
            } else if (parkingPlaceUseInfo.getPayFlag().equals("2")) {
                parkingPlaceUseInfoResult.setParkingPlaceStatusStr("预约取消");
            } else {
                if (parkingPlaceInfo.getStatus().equals("0")) {
                    parkingPlaceUseInfoResult.setParkingPlaceStatusStr("");
                } else if (parkingPlaceInfo.getStatus().equals("1")) {
                    parkingPlaceUseInfoResult.setParkingPlaceStatusStr("停车中");
                } else if (parkingPlaceInfo.getStatus().equals("2")) {
                    parkingPlaceUseInfoResult.setParkingPlaceStatusStr("预定中");
                } else if (parkingPlaceInfo.getStatus().equals("3")) {
                    parkingPlaceUseInfoResult.setParkingPlaceStatusStr("");
                }
            }

        });
        map.put("parkingPlaceUseInfos", list);
        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    @PostMapping(value = "begin/use")
    @Transactional(rollbackFor = Exception.class)
    public Object beginUse(ParkingPlaceUseInfoParam parkingPlaceUseInfoParam) {
        Map map = new HashMap();
        //锁定车位
        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfoParam.getParkingPlaceId());
        parkingPlaceInfo.setStatus("1");
        parkingPlaceInfoService.saveOrUpdate(parkingPlaceInfo);

        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getOne(new QueryWrapper<ParkingPlaceUseInfo>().eq("parking_place_id", parkingPlaceUseInfoParam.getParkingPlaceId()).eq("pay_flag", 1).eq("open_id", parkingPlaceUseInfoParam.getOpenId()));
        parkingPlaceUseInfo.setParkStartTime(new DateTime());
        parkingPlaceUseInfoService.saveOrUpdate(parkingPlaceUseInfo);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    // 取消预约
    @PostMapping(value = "cancel/order")
    @Transactional(rollbackFor = Exception.class)
    public Object cancelOrder(ParkingPlaceUseInfoParam parkingPlaceUseInfoParam) {
        Map map = new HashMap();

        // 变成支付状态
        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getOne(new QueryWrapper<ParkingPlaceUseInfo>().eq("parking_place_id", parkingPlaceUseInfoParam.getParkingPlaceId()).eq("pay_flag", 1).eq("open_id", parkingPlaceUseInfoParam.getOpenId()));
        parkingPlaceUseInfo.setPayFlag("2");
        parkingPlaceUseInfo.setOrderTime(null);
        parkingPlaceUseInfoService.saveOrUpdate(parkingPlaceUseInfo);

        //释放车位
        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfoParam.getParkingPlaceId());
        parkingPlaceInfo.setStatus("0");
        parkingPlaceInfoService.saveOrUpdate(parkingPlaceInfo);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    @PostMapping(value = "car/out")
    @Transactional(rollbackFor = Exception.class)
    public Object carOut(ParkingPlaceUseInfoParam parkingPlaceUseInfoParam) {
        Map map = new HashMap();

        WxMiniUser wxMiniUserSub = wxMiniUserService.getOne(new QueryWrapper<WxMiniUser>().eq("open_id", parkingPlaceUseInfoParam.getOpenId()));
        if (wxMiniUserSub.getMoney().compareTo(BigDecimal.valueOf(parkingPlaceUseInfoParam.getMoney())) < 0) {
            ErrorResponseData errorResponseData = new ErrorResponseData("余额不足，请先充值。");
            errorResponseData.setData(map);
            return errorResponseData;
        }

        // 变成支付状态
        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getOne(new QueryWrapper<ParkingPlaceUseInfo>().eq("parking_place_id", parkingPlaceUseInfoParam.getParkingPlaceId()).eq("pay_flag", 1).eq("open_id", parkingPlaceUseInfoParam.getOpenId()));
        parkingPlaceUseInfo.setPayFlag("0");
        parkingPlaceUseInfo.setMoney(parkingPlaceUseInfoParam.getMoney());
        parkingPlaceUseInfo.setPayTime(new DateTime());
        parkingPlaceUseInfoService.saveOrUpdate(parkingPlaceUseInfo);

        //释放车位
        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfoParam.getParkingPlaceId());
        parkingPlaceInfo.setStatus("0");
        parkingPlaceInfoService.saveOrUpdate(parkingPlaceInfo);

        // 减钱
        wxMiniUserSub.setMoney(wxMiniUserSub.getMoney().subtract(BigDecimal.valueOf(parkingPlaceUseInfoParam.getMoney())));
        wxMiniUserService.updateById(wxMiniUserSub);
        // 加钱
        // 找车位主人
        WxMiniUser wxMiniUserPlus = wxMiniUserService.getOne(new QueryWrapper<WxMiniUser>().eq("open_id", parkingPlaceInfo.getOpenId()));
        if (wxMiniUserPlus != null) {
            wxMiniUserPlus.setMoney(wxMiniUserPlus.getMoney().add(BigDecimal.valueOf(parkingPlaceUseInfoParam.getMoney())));
            wxMiniUserService.updateById(wxMiniUserPlus);
        }
        //日志
        // 减少的
        MoneyHistory moneyHistory = new MoneyHistory();
        moneyHistory.setType("2");
        moneyHistory.setOpenId(parkingPlaceUseInfoParam.getOpenId());
        moneyHistory.setMoney(BigDecimal.valueOf(parkingPlaceUseInfoParam.getMoney()));
        moneyHistory.setCreateTime(new DateTime());
        moneyHistoryService.save(moneyHistory);
        // 增加的
        moneyHistory = new MoneyHistory();
        moneyHistory.setType("3");
        moneyHistory.setOpenId(parkingPlaceInfo.getOpenId());
        moneyHistory.setMoney(BigDecimal.valueOf(parkingPlaceUseInfoParam.getMoney()));
        moneyHistory.setCreateTime(new DateTime());
        moneyHistoryService.save(moneyHistory);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    // 预约
    @PostMapping(value = "order")
    @Transactional(rollbackFor = Exception.class)
    public Object order(ParkingPlaceUseInfoParam parkingPlaceUseInfoParam) {
        Map map = new HashMap();

        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getOne(new QueryWrapper<ParkingPlaceUseInfo>().eq("open_id", parkingPlaceUseInfoParam.getOpenId()).eq("pay_flag", 1));
        if (parkingPlaceUseInfo != null) {

            ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfo.getParkingPlaceId());
            if ("2".equals(parkingPlaceInfo.getStatus())) {
                ErrorResponseData errorResponseData = new ErrorResponseData("请勿重复预约");
                return errorResponseData;
            } else if ("1".equals(parkingPlaceInfo.getStatus())) {
                ErrorResponseData errorResponseData = new ErrorResponseData("您已在停车中");
                return errorResponseData;
            }
        }
        String orderTime = parkingPlaceUseInfoParam.getOrderTime();
        parkingPlaceUseInfoParam.setOrderTime(DateUtil.today() + " " + orderTime);
        parkingPlaceUseInfoService.add(parkingPlaceUseInfoParam);

        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfoParam.getParkingPlaceId());
        // 未支付相当于预约中
        parkingPlaceInfo.setStatus("2");
        parkingPlaceInfoService.saveOrUpdate(parkingPlaceInfo);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }

    @PostMapping(value = "use/now")
    @Transactional(rollbackFor = Exception.class)
    public Object useNow(ParkingPlaceUseInfoParam parkingPlaceUseInfoParam) {
        Map map = new HashMap();

        ParkingPlaceUseInfo parkingPlaceUseInfo = parkingPlaceUseInfoService.getOne(new QueryWrapper<ParkingPlaceUseInfo>().eq("open_id", parkingPlaceUseInfoParam.getOpenId()).eq("pay_flag", 1));
        if (parkingPlaceUseInfo != null) {

            ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfo.getParkingPlaceId());
            if ("2".equals(parkingPlaceInfo.getStatus())) {
                ErrorResponseData errorResponseData = new ErrorResponseData("您已预约车位");
                return errorResponseData;
            } else if ("1".equals(parkingPlaceInfo.getStatus())) {
                ErrorResponseData errorResponseData = new ErrorResponseData("请勿重复降锁");
                return errorResponseData;
            }
        }
        parkingPlaceUseInfoParam.setParkStartTime(new DateTime());
        parkingPlaceUseInfoService.add(parkingPlaceUseInfoParam);

        ParkingPlaceInfo parkingPlaceInfo = parkingPlaceInfoService.getById(parkingPlaceUseInfoParam.getParkingPlaceId());
        // 使用中
        parkingPlaceInfo.setStatus("1");
        parkingPlaceInfoService.saveOrUpdate(parkingPlaceInfo);

        SUCCESS_TIP.setData(map);
        return SUCCESS_TIP;
    }
}


